<template>
  <div class="file-upload">
    <el-upload
      class="avatar-uploader"
      action=""
      :http-request="handleRequest"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload">
      <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="课程封面">
      <el-progress v-else-if="uploading" type="circle" :percentage="percentage"
        class="avatar-uploader-progress" :width="178"></el-progress>
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <el-tag type="info">{{ title }}</el-tag>
  </div>

</template>
<script>
// eslint-disable-next-line
import { uploadCourseImage } from '@/services/course';

export default {
  name: 'FileUpload',
  props: ['value', 'title'],
  data() {
    return {
      fileType: ['image/jpeg', 'image/png'],
      fileMaxSize: 150 * 1024,
      imageUrl: this.value,
      uploading: false,
      percentage: 0,
    };
  },
  watch: {
    value(val) {
      this.imageUrl = val;
    },
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const typeCheck = this.fileType.includes(file.type);
      const sizeCheck = file.size <= this.fileMaxSize;
      if (!typeCheck) {
        this.$message.error('上传头像图片只能是 JPG|PNG 格式!');
      }
      if (!sizeCheck) {
        this.$message.error('上传头像图片大小不能超过 150KB!');
      }
      return typeCheck && sizeCheck;
    },
    async handleRequest(options) {
      this.uploading = true;
      const fd = new FormData();
      fd.append('file', options.file);
      const { data } = await uploadCourseImage(fd, (event) => {
        this.percentage = Math.floor((event.loaded / event.total) * 100);
      });
      if (data.code === '000000') {
        const filename = data.data.name;
        this.imageUrl = filename;
        this.$emit('input', filename);
        this.$message.success('文件上传成功');
      } else {
        this.$message.error('文件上传失败');
      }
      this.uploading = false;
    },
  },
};
</script>
<style scoped>
::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
